package com.thinkgem.dingdan.common.file;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "${adminPath}/file")
public class FileUploadController {

	@Value("${aliyunAccessKey}")
	private String accessKey;
	@Value("${aliyunSecretKey}")
	private String secretKey;
	@Value("${aliyunOrderBucket}")
	private String bucket;
	@Value("${aliyunPicPrefixUrl}")
	private String picPrefix;

	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(FileUploadController.class);

	@RequestMapping(value = "uploadFile", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	public void uploadFile(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file) {
		Map<String,Object> map = new HashMap<>();
		try {
			if (file != null) {
				String fileName = new Date().getTime() + ".png";
				logger.info(fileName);
				byte[] uploadBytes = toByteArray(file.getInputStream());
				SevenCattleUploadUtil.result(accessKey, secretKey, bucket, uploadBytes, fileName);
				map.put("flag", true);
				map.put("val", fileName);
				map.put("picPrefix", picPrefix);
				JSONObject json = JSONObject.parseObject(JSON.toJSONString(map));
				response.getWriter().write(json.toString());
				response.setHeader("Access-Control-Allow-Origin", "*");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("上传图片失败", e);
		}
	}

	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}

}
